package com.doubao.file.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MinIO配置类
 */
@Configuration
@Data
@Slf4j
public class MinioConfig {
    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.avatar-bucket}")
    private String avatarBucket;

    @Value("${minio.chat-bucket}")
    private String chatBucket;

    @Value("${minio.connect-timeout:10000}")
    private int connectTimeout;

    @Value("${minio.retry-count:3}")
    private int retryCount;

    @Bean
    public MinioClient minioClient() {
        try {
            log.info("正在初始化 MinIO 客户端: endpoint={}", endpoint);
            
            // 创建客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();

            // 测试连接
            minioClient.listBuckets();
            log.info("MinIO 连接测试成功");

            // 使用重试机制创建存储桶
            retryOperation(() -> createBucketIfNotExists(minioClient, bucketName));
            retryOperation(() -> createBucketIfNotExists(minioClient, avatarBucket));
            retryOperation(() -> createBucketIfNotExists(minioClient, chatBucket));

            return minioClient;
        } catch (Exception e) {
            log.error("MinIO 客户端初始化失败", e);
            throw new RuntimeException("MinIO 客户端初始化失败: " + e.getMessage());
        }
    }

    private void createBucketIfNotExists(MinioClient minioClient, String bucket) {
        try {
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
                log.info("创建存储桶成功: {}", bucket);
            } else {
                log.info("存储桶已存在: {}", bucket);
            }
        } catch (Exception e) {
            log.error("存储桶操作失败: {}", bucket, e);
            throw new RuntimeException("存储桶操作失败: " + bucket, e);
        }
    }

    private void retryOperation(Runnable operation) {
        int attempts = 0;
        while (attempts < retryCount) {
            try {
                operation.run();
                return;
            } catch (Exception e) {
                attempts++;
                if (attempts == retryCount) {
                    throw e;
                }
                log.warn("操作失败，准备第 {} 次重试", attempts + 1);
                try {
                    Thread.sleep(1000 * attempts); // 递增延迟
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("重试被中断", ie);
                }
            }
        }
    }
}